import { defineStore } from 'pinia'
import { http, authHttp } from '@/utils/http/index.js'
import { showExpertAvator } from '@/utils/index.js'
import { uploadFile } from '@/utils/file.js'
import { ElLoading, ElMessage } from 'element-plus'
import { ContentTypeEnum } from '@/enums/httpEnum.js'

/**用户权限store */
export const useAuthStore = defineStore('auth', {
  state: () => {
    return {
      /**用户信息 */
      userInfo: '',
      /**访问令牌 */
      auth_token: '',
      /**过期时间 */
      expirationTime: ''
    }
  },
  getters: {
    /**仅用于画面显示是否登录使用 */
    isLoggedIn: (state) => state.auth_token,
    /**是否为专家 */
    isExpert() {
      return this.userInfo?.roles?.includes('宣讲专家')
    },
    /**获取专家头像 */
    expertAvatar() {
      return showExpertAvator(this.userInfo?.expertInfo || {})
    }
  },
  actions: {
    /**用户登录 */
    getUserInfo() {
      const loading = ElLoading.service()
      return new Promise((resolve, reject) => {
        authHttp
          .$GET('/Auth/GetUserInfo', { authtoken: this.auth_token })
          .then((res) => {
            if (res.isError) return reject()
            this.userInfo = res.result
            resolve()
          })
          .finally(() => loading.close())
      })
    },
    /**设置权限过期时间 */
    setExperTime() {
      this.expirationTime = new Date().getTime() + 24 * 60 * 60 * 1000
    },
    /**
     * 主动判断权限是否过期
     **/
    isExpired(needTipClean = false) {
      const tempFlag = !this.expirationTime || new Date().getTime() > this.expirationTime
      /**过期时需要提示并且清除用户信息 */
      if (needTipClean && tempFlag) {
        ElMessage.warning('当前暂未登录')
        this.cleanAuthInfo()
      }
      return tempFlag
    },
    /**去登陆 */
    toLoginPage(returnUrl) {
      const appId = '1716655616539271168'
      const scope = 'auth_base'
      if (!returnUrl) returnUrl = window.location.href
      window.open(
        `${
          import.meta.env.VITE_APP_AUTH_ORIGIN
        }/Home/Login?AppId=${appId}&Scope=${scope}&RedirectUri=${
          import.meta.env.VITE_APP_BACKEND_ORIGIN
        }/Auth/AuthHandler?return_url=${returnUrl}`,
        '_self'
      )
    },
    /**退出登录 */
    logout(returnUrl) {
      if (!returnUrl) returnUrl = window.location.origin
      this.cleanAuthInfo()
      window.open(
        `${import.meta.env.VITE_APP_AUTH_ORIGIN}/Home/Logout?returnUrl=${returnUrl}`,
        '_self'
      )
    },
    /**清除登录信息 */
    cleanAuthInfo() {
      this.userInfo = ''
      this.auth_token = ''
      this.expirationTime = ''
      localStorage.removeItem('auth')
    },
    /**查询专家id */
    async setExpertInfo() {
      const res = await http.$GET('/Expert/GetExpertInfoDetail', {id: this.userInfo.expertId})
      if (res.isError) return
      this.userInfo.expertInfo = res.result
    },
    /**更换专家头像 */
    changeExpertAvatar() {
      uploadFile({ accept: '.jpg,.jpeg,.png,.JPG,.JPEG,.PNG' }).then((files) => {
        http
          .$POST(
            '/TheoryStudyM/AddOrUpdateExpertInfo',
            { id: this.userInfo.expertId, ExpertPic: files[0] },
            {
              headers: { 'Content-Type': ContentTypeEnum.FORM_DATA }
            }
          )
          .then((res) => {
            if (res.IsError) return
            ElMessage.success('更新成功')
            this.setExpertInfo()
          })
      })
    }
  },
  persist: {
    // 存储位置，默认 localStorage
    storage: localStorage,
    // afterRestore: async (context) => {
    //   const authStore = context.store
    //   /**权限没过期的操作 */
    //   if (!authStore.isExpired()) {
    //     /**如果是专家权限则设置专家id */
    //     if (authStore?.userInfo?.roles?.includes('宣讲专家')) {
    //       await authStore.getExpertInfo()
    //     }
    //   }
    // }
  }
})
